package com.wendyxie.sproutup.view

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.navigation.fragment.findNavController
import com.wendyxie.sproutup.R
import com.wendyxie.sproutup.databinding.ActivityMainBinding
import com.wendyxie.sproutup.db.SQLInitHelper
import com.wendyxie.sproutup.db.SQLUserHelper
import com.wendyxie.sproutup.db.SQLUserScoreRecordHelper
import com.wendyxie.sproutup.entity.UserScoreRecordEntity
import com.wendyxie.sproutup.enum.ScoreStatusEnum
import com.wendyxie.sproutup.service.Task
import com.wendyxie.sproutup.utils.SPUtil

class MainActivity : AppCompatActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var binding: ActivityMainBinding
    private var waterNumList = mutableListOf<UserScoreRecordEntity>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setSupportActionBar(binding.toolbar)

        // 初始化数据
//        SQLInitHelper(binding.root.context).openDatabase()

        // 启动时：检查
//        Task().checkUserScoreRecordTask(this)

        // 按钮：跳转到【收集记录】页面
        binding.includeMain.btnUserRecord.setOnClickListener {
            // 打开页面UserScoreRecordActivity
            val intent = Intent(binding.root.context, UserScoreRecordActivity::class.java)
            startActivity(intent)
        }
        // 按钮：全部收集
        binding.includeMain.btnCollectEnergy.setOnClickListener {
            val scoreRecordEntity = UserScoreRecordEntity(ScoreStatusEnum.COLLECT)
            scoreRecordEntity.babyId = SPUtil.getBabyId(binding.root.context)
            SQLUserScoreRecordHelper.collectUserScoreRecordAll(scoreRecordEntity, SQLInitHelper(binding.root.context).openDatabase())
            Toast.makeText(binding.root.context, "全部收集成功", Toast.LENGTH_SHORT).show()
            refreshWater()
        }
        // 按钮：更换皮肤
        binding.includeMain.btnChangeSkin.setOnClickListener {
            // 打开页面ChangeSkinActivity
            val intent = Intent(binding.root.context, ChangeSkinActivity::class.java)
            startActivity(intent)
        }
    }

    override fun onResume() {
        super.onResume()
        // 查询用户的信息
        val babyId = SPUtil.getBabyId(binding.root.context)
        val userEntity = SQLUserHelper.queryBabyById(babyId, SQLInitHelper(binding.root.context).openDatabase())
        Log.d("FirstFragment", "userEntity = $userEntity")
        binding.includeMain.imageTree.setImageResource(
            binding.root.context.resources.getIdentifier(userEntity.selectedTreeSkinUrl.replace("R.mipmap.", ""), "mipmap", binding.root.context.packageName)
        )
        onPostResume()
        refreshWater()
    }


    private fun refreshWater() {
        // 显示待收：查询待收取的列表
        val scoreRecordEntity = UserScoreRecordEntity(ScoreStatusEnum.CREATE)
        val recordList = SQLUserScoreRecordHelper.queryRecordListByScoreStatus(scoreRecordEntity, SQLInitHelper(binding.root.context).openDatabase())
        setWaterNumList(recordList)

        // 进度条显示：查询总共的分数
        val userEntity = SQLUserHelper.queryBabyById(SPUtil.getBabyId(binding.root.context), SQLInitHelper(binding.root.context).openDatabase())
        val currentTotalScore = userEntity.currentTotalScore ?: 0
        binding.includeMain.tvTotalScore.text = "共 $currentTotalScore g"
    }

    /**
     * 设置参数，设置参数后，刷新页面
     */
    private fun setWaterNumList(itemList: List<UserScoreRecordEntity>) {
        waterNumList.clear()
        waterNumList.addAll(itemList)
        binding.includeMain.mWaterFlake.setModelList(waterNumList, binding.includeMain.imageTree)
        binding.includeMain.mWaterFlake.setOnWaterItemListener {
            //TODO 收集事件
        }
        // 刷新水滴收取的位置
        binding.includeMain.imageTree.post(Runnable {
            binding.includeMain.mWaterFlake.setXY(binding.includeMain.imageTree)
        })
    }


    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_settings -> {
                // 打开页面
                val intent = Intent(this, ParentPwdActivity::class.java)
                startActivity(intent)
                return true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }
}
